package com.my.stock.core;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

import org.zeromq.ZMQ;

import util.JavaFile;

public class ShowMeTheMoney3 {

	public static BlockingQueue<String> subQueue = new ArrayBlockingQueue<String>(1024);

	public Thread tickSUBThread = new Thread(new Runnable() {

		public void run() {
			ZMQ.Context context = ZMQ.context(1);
			ZMQ.Socket s = context.socket(ZMQ.SUB);
			s.connect("tcp://127.0.0.1:5556");
			s.subscribe("".getBytes());
			while (true) {
				byte recStr[] = s.recv();
				if (recStr == null) {
					continue;
				}
				String sg = "";
				try {
					sg = new String(recStr, "gb2312");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				if (subQueue.offer(sg)) {

				} else {
					System.out.println("SUB ERROR!!!!");
				}
			}
		}

	});

	public Thread tickThread = new Thread(new Runnable() {

		public void run() {

			while (true) {
				String sg = "";
				try {
					sg = subQueue.take();
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}

				if (sg.equals("")) {
					continue;
				}

//					System.out.println(sg);
				if (sg.startsWith("errorOrder")) {

					System.out.println("下单错误！！！" + sg);

				} else if (sg.startsWith("queryOrder")) {
					String code = sg.split(",")[1];
					Product p = productMap.get(code);
					if (Integer.parseInt(sg.split(",")[3]) == 0) {
						continue;
					}
					p.setOwnPosition(p.getOwnPosition() + Integer.parseInt(sg.split(",")[3]));
					p.setOrderPrice(
							Double.parseDouble(sg.split(",")[4]) / Integer.parseInt(sg.split(",")[3]) / p.getUnit());
					p.setOnPosition(true);
					System.out
							.println("当前持仓：" + p.getCode() + " 数量：" + p.getOwnPosition() + " 价格:" + p.getOrderPrice());
				} else if (sg.startsWith("OKOrder")) {

					// 订单提交成功
					if (sg.split(",")[3].equals("3")) {
						// 撤单成功
						if (sg.split(",")[4].equals("5")) {
							String code = sg.split(",")[1];
							Product p = productMap.get(code);
							if (p == null) {
								continue;
							}

							if (sg.split(",")[8].equals("0")) {
								p.setPoolInsertOrderNum(
										p.getPoolInsertOrderNum() - Integer.parseInt(sg.split(",")[11]));
							} else {
								p.setPoolStopOrderNum(p.getPoolStopOrderNum() - Integer.parseInt(sg.split(",")[11]));
							}
							p.setDone(false);
							System.out.println("撤单成功！！！" + sg);
						} else if (sg.split(",")[4].equals("0")) {
							// 成交
//							String code = sg.split(",")[1];
//							Product p = productMap.get(code);
//
//							if (p == null) {
//								System.out.println(code);
//								continue;
//							}
//
//							if (sg.split(",")[8].equals("0")) {
//								// 开仓
//								p.setPoolInsertOrderNum(p.getPoolInsertOrderNum() - Integer.parseInt(sg.split(",")[2]));
//
//							} else {
//								// 平仓
//								p.setPoolStopOrderNum(p.getPoolStopOrderNum() - Integer.parseInt(sg.split(",")[2]));
//								p.setCloseOrderTime(System.currentTimeMillis());
//								p.setStopLossPrice(0);
//							}
//							System.out.println("订单成交！！！" + sg);
						} else if (sg.split(",")[4].equals("3")) {

							// 下单
							Product p = productMap.get(sg.split(",")[1]);

							if (p == null) {
								continue;
							}

							p.setExchangeID(sg.split(",")[5]);
							//
							String po = sg.split(",")[6];
							int len = po.length();
							for (int i = 0; i < 12 - len; i++) {
								po = " " + po;
							}
							p.setParkedOrderID(po);
							p.setInstrumentID(sg.split(",")[7]);
							//
							p.setPoolOrderPrice(Double.parseDouble(sg.split(",")[9]));
							String or = sg.split(",")[10];
							//
							len = or.length();
							for (int i = 0; i < 12 - len; i++) {
								or = " " + or;
							}
							if (Integer.parseInt(sg.split(",")[12]) == 0) {
								// 开仓
								p.setInsertOrderRef(or);
								cancelOrder(p.getCode(), 0);
							} else {
								// 平仓
								p.setStopOrderRef(or);
								cancelOrder(p.getCode(), 1);
							}
							//

							System.out.println("下单成功！！！" + sg);

						}
					}

				} else {

					long log = DateUtil.getNowDateTimeT(sg.split(",")[6]);
					if (log > 2000) {
						System.out.println("警告超时！！！" + log + "ms");
					} else {
						processTick(sg);
					}

				}

			}
		}

	});

	private boolean closeCondition(Product p, double buyPrice, double sellPrice) {
		Date d = new Date();

		if (d.getHours() == 14 && d.getMinutes() >= 50) {
			return true;
		} else {
			return false;
		}

	}

	public void processTick(String tick) {

		String code = tick.split(",")[0];
		Product p = productMap.get(code);
		if (p != null) {
			System.out.println(tick);
			if (!p.isOnPosition()) {

				double buyPrice = Double.parseDouble(tick.split(",")[3]);
				double sellPrice = Double.parseDouble(tick.split(",")[2]);
				int buyVolume = Integer.parseInt(tick.split(",")[8]);
				int sellVolume = Integer.parseInt(tick.split(",")[7]);

				System.out.println(buyPrice);
				System.out.println(p.getOpenBuyPrice());
				System.out.println(sellPrice);
				System.out.println(p.getOpenSellPrice());

				if (buyPrice >= p.getHighestPrice() || sellPrice <= p.getLowestPrice()) {

					insertOrder(code, sellPrice, buyPrice);
					p.setOnPosition(true);

				}

			}

		}

	}

	// 检查下单条件
	private String checkInsertOrder(String code, double buyPrice, double sellPrice) {
		Date d = new Date();
		Product p = productMap.get(code);

		if (d.getHours() == 14 && d.getMinutes() > 30 || d.getHours() == 15) {
			return "";
		} else {
			if (p.getPoolInsertOrderNum() == 0 && p.getCloseOrderTime() == 0 && p.getOrderTime() == 0) {

				if (buyPrice < p.getOpenBuyPrice() - p.getMinStep() * p.getStopLossStep()) {
					return "sell";
				}
				if (sellPrice > p.getOpenSellPrice() + p.getMinStep() * p.getStopLossStep()) {
					return "buy";
				}

			} else {
				return "";
			}
		}
		return "";
	}

	private void insertOrder(String code, double buyPrice, double sellPrice) {
		Product p = productMap.get(code);
		p.setPoolInsertOrderNum(p.getMaxOrderNum());
		p.setOwnPosition(p.getMaxOrderNum());

		p.setOpenBuyPrice(sellPrice);
		p.setOpenSellPrice(buyPrice);
		p.setOrderTime(System.currentTimeMillis());
		String order = "shortstop," + code + "," + p.getPoolInsertOrderNum() + "," + sellPrice + "," + buyPrice + "\0";
		signalQueue.offer(order);
//		String order1 = "sell," + code + "," + p.getPoolInsertOrderNum() + "," + sellPrice + "," + buyPrice + "\0";
//		signalQueue.offer(order1);

	}

	private void closePositon(String code, double buyPrice, double sellPrice) {
		System.out.print("止盈" + code);
		Product p = productMap.get(code);
		String type = p.getTradeType();
		if (type.equals("buy")) {
			type = "sell";
		} else {
			type = "buy";
		}

		String order = type + "," + code + "," + p.getOwnPosition() + "," + sellPrice + "," + buyPrice + "\0";

		signalQueue.offer(order);

	}

	// 停损
	private void stopLoss(String code, double buyPrice, double sellPrice) {
		System.out.print("停损" + code + "！！！");
		Product p = productMap.get(code);
		String type = p.getTradeType();
		if (type.equals("buy")) {
			type = "sell";
		} else {
			type = "buy";
		}
		String order = type + "," + code + "," + p.getOwnPosition() + "," + sellPrice + "," + buyPrice + "\0";
		signalQueue.offer(order);
	}

	private void cancelOrder(String code, int combOffsetFlag) {

		Product p = productMap.get(code);
		String type = "cancel";

		String or = "";
		if (combOffsetFlag == 0) {
			if (p.getInsertOrderRef().equals("")) {
				return;
			} else {
				or = p.getInsertOrderRef();
				p.setInsertOrderRef("");
			}

		} else {
			if (p.getStopOrderRef().equals("")) {
				return;
			} else {
				or = p.getStopOrderRef();
				p.setStopOrderRef("");
			}
		}

		String order = type + "," + p.getExchangeID() + "," + p.getParkedOrderID() + "," + p.getInstrumentID() + ","
				+ or + "\0";

		cancelList.add(order);

	}

	private static Map<String, Product> productMap = new HashMap<String, Product>();

	public static BlockingQueue<String> signalQueue = new ArrayBlockingQueue<String>(1024);

	public static List<String> cancelList = new ArrayList<String>();

	Thread tradeThread = new Thread(new Runnable() {
		public void run() {
			ZMQ.Context context = ZMQ.context(1);
			ZMQ.Socket s = context.socket(ZMQ.REQ);
			s.connect("tcp://*:5557");
//			signalQueue.offer("queryOrder,a");
			while (true) {
				String trade;
				try {
					trade = signalQueue.take();
					System.out.println(trade);
					s.send(trade.getBytes(), 0);
					s.recv(0);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

			}
		}
	});

	public static void main(String[] args) throws IOException {
//		String or = "13";
//		System.out.println();
//		int len =or.length();
//		for (int i = 0; i < 12 - len; i++) {
//			or = " " + or;
//		}
//		System.out.println(or);
		List<String> config = JavaFile.readfile("d:\\show.txt");

		for (String c : config) {
			Product p = new Product();
			p.setCode(c.split(",")[0]);
			p.setContractName(c.split(",")[1]);
			p.setMaxOrderNum(Integer.parseInt(c.split(",")[3]));
			p.setMinStep(Double.parseDouble(c.split(",")[4]));
			p.setUnit(Integer.parseInt(c.split(",")[5]));
			p.setStrategy(c.split(",")[6]);
			p.setStopLossStep(Integer.parseInt(c.split(",")[7]));
			p.setTriggerVolume(Double.parseDouble(c.split(",")[8]));
			productMap.put(c.split(",")[0], p);
			System.out.println(p.getContractName());
		}

		ShowMeTheMoney4 s = new ShowMeTheMoney4();
		s.tickThread.start();
		s.tickSUBThread.start();
		s.tradeThread.start();

	}
}
